package alg20241118;

public class Text2 {
    public int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        //1  创建表
        int[][] dp = new int[m + 1][n + 2];
        //2  初始化
        for (int i = 1; i <= n; i++) {
            dp[i][0] = dp[i][n+1] = Integer.MAX_VALUE;
        }

        //3  填表
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = Math.min(Math.min(dp[i-1][j-1], dp[i-1][j]), dp[i-1][j+1]) + matrix[i-1][j-1];
            }
        }
        //4  返回值
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < dp[0].length; i++) {
            if(dp[m][i] < min){
                min = dp[m][i];
            }
        }
        return min;
    }
}
